//
//  YWAssignInspectionMissionTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/6.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAssignInspectionMissionTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"
#import "YWLoginTool.h"

#import "YWHandler.h"
#import "YWInspectionMissionModel.h"
#import "YWInspectionMissionManager.h"

#import "YWSelectContactTableViewController.h"
#import "YWSelectInspectionLineTableViewController.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWSelectBuildingTableViewController.h"

static CGFloat const kDatePickerViewH = 216;
static CGFloat const kInspectionStartDateTag = 20;
static CGFloat const kInspectionEndDateTag = 21;
static CGFloat const kInspectionStartTimeTag = 30;
static CGFloat const kInspectionEndTimeTag = 31;

@interface YWAssignInspectionMissionTableViewController ()<YWSelectBuildingTableViewControllerDelegate,YWContactVCSelectContactDelegate,YWSelectInspectionLineTableViewControllerDelegate>{
    YWBuilding *currentBuilding;
    YWInspectionLineOption *currentInspectionLineOption;
    NSString *startDate;
    NSString *endDate;
    NSString *startTime;
    NSString *endTime;
    BOOL isShowDatePicker;
    NSInteger currentTag;
}
@property (nonatomic, strong) NSArray *allBuildings;
@property (nonatomic, strong) NSMutableArray *executors;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWAssignInspectionMissionTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"assignInspectionMission", nil);
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickCancelBarButtonEvent:)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDeleteInspectionLineNotiEvent:) name:KRefreshDeleteInspectionLineNotification object:nil];
    
    [self setupData];
    [self initTableView];
}

- (void)setupData{
    currentBuilding = self.allBuildings.count>0?self.allBuildings[0]:nil;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *string = [formatter stringFromDate:[NSDate date]];
    startDate = string;
    //endDate = string;
    startTime = @"00:00";
    endTime = @"23:59";
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    [self.datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
}

- (void)refreshDeleteInspectionLineNotiEvent:(NSNotification*)noti{
    NSInteger lineId = [noti.object integerValue];
    if (lineId == currentInspectionLineOption.inspectionLineId) {
        currentInspectionLineOption = nil;
        [self.tableView reloadData];
    }
}

- (NSArray *)allBuildings{
    if (!_allBuildings) {
        _allBuildings = [[YWBuildingManager shareManager] allBuilding];
    }
    return _allBuildings;
}
- (NSMutableArray *)executors{
    if (!_executors) {
        _executors = [NSMutableArray array];
    }
    return _executors;
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
        return self.executors.count > 0 ? self.executors.count : 1;
    }else if (section == 3 || section == 4){
        return 2;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"YWAssignInspectionMissionVCReuseCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = kContentFont;
        cell.detailTextLabel.font = kContentFont;
    }
    if (indexPath.section == 0) {
        NSString *buildingShowName = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"pleaseSelect", nil),[YWLoginTool buildingShowName]];
        cell.textLabel.text = currentBuilding ? currentBuilding.buildingName?:@"未知" : buildingShowName;
    }else if (indexPath.section == 1) {
        cell.textLabel.text = currentInspectionLineOption ? currentInspectionLineOption.inspectionLineName?:NSLocalizedString(@"unknowLine", nil) : NSLocalizedString(@"pleaseSelectInspectionLine", nil);
    }else if (indexPath.section ==2){
        if (self.executors.count>0) {
            YWHandler *handler = self.executors[indexPath.row];
            cell.textLabel.text = handler.userName?:@"";
        }else{
            cell.textLabel.text = NSLocalizedString(@"pleaseSelectExecutor", nil);
        }
    }else if (indexPath.section == 3){
        cell.textLabel.text = indexPath.row==0 ? [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"startDate", nil),startDate?:NSLocalizedString(@"pleaseSelect", nil)]:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"endDate", nil),endDate?:NSLocalizedString(@"pleaseSelect", nil)];
    }else if (indexPath.section == 4){
        NSString *timeString = indexPath.row==0 ? [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"startTime", nil),startTime?:NSLocalizedString(@"pleaseSelect", nil)]:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"endTime", nil),endTime?:NSLocalizedString(@"pleaseSelect", nil)];
        if (indexPath.row==1 && startTime.length>0 && endTime.length>0 && [[startTime stringByReplacingOccurrencesOfString:@":" withString:@""] integerValue]>[[endTime stringByReplacingOccurrencesOfString:@":" withString:@""] integerValue]) {
            cell.textLabel.text = [NSString stringWithFormat:@"%@第二天",timeString];
        }else{
            cell.textLabel.text = timeString;
        }
    }
    
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.section == 2 && [self.executors count]>0) ? UITableViewCellEditingStyleDelete : UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2 && [self.executors count]>0) {
        [self.executors removeObjectAtIndex:indexPath.row];
        if (self.executors.count==0) {
            [tableView reloadData];
        }else{
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWAssignInspectionMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        return buildingShowName.length?buildingShowName:NSLocalizedString(@"building", nil);
    }else if (section == 1) {
        return NSLocalizedString(@"inspectionLine", nil);//@"巡查路线";
    }else if (section==2){
        return NSLocalizedString(@"executor", nil);//@"执行人";
    }else if (section==3){
        return NSLocalizedString(@"inspectionStartAndEndDate", nil);//@"巡查任务起止日期";
    }else if (section==4){
        return NSLocalizedString(@"inspectiontartAndEndTime", nil);//@"每天巡查起止时间";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
        selectBuildingVC.delegate = self;
        selectBuildingVC.ownBuilding = currentBuilding;
        [self.navigationController pushViewController:selectBuildingVC animated:YES];
    }else if (indexPath.section == 1) {
        if (currentBuilding) {
            YWSelectInspectionLineTableViewController *selectInspectionLineVC = [[YWSelectInspectionLineTableViewController alloc] init];
            selectInspectionLineVC.delegate = self;
            selectInspectionLineVC.building = currentBuilding;
            selectInspectionLineVC.ownInspectionLineOption = currentInspectionLineOption;
            [self.navigationController pushViewController:selectInspectionLineVC animated:YES];
        }else{
            NSString *buildingShowName = [YWLoginTool buildingShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"firstSelect", nil),buildingShowName]];
        }
    }else if (indexPath.section == 2){
        if (currentBuilding.buildingId.length) {
            YWSelectContactTableViewController *selectContactVC = [[YWSelectContactTableViewController alloc] init];
            selectContactVC.delegate = self;
            selectContactVC.buildingId = currentBuilding.buildingId;
            selectContactVC.isMultiSelect = YES;
            selectContactVC.ownContacts = self.executors;
            selectContactVC.titleName = NSLocalizedString(@"selectExecutor", nil);
            [self.navigationController pushViewController:selectContactVC animated:YES];
        }else{
            NSString *buildingShowName = [YWLoginTool buildingShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"firstSelect", nil),buildingShowName]];
        }
        
    }else if (indexPath.section == 3 || indexPath.section == 4){
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        CGFloat offsetY = self.tableView.contentSize.height -self.tableView.bounds.size.height;
        if (indexPath.section == 3) {
            if (offsetY>=0) {
                [self.tableView setContentOffset:CGPointMake(0, offsetY) animated:YES];
            }
            currentTag = indexPath.row == 0 ? kInspectionStartDateTag : kInspectionEndDateTag;
            _datePicker.datePickerMode = UIDatePickerModeDate;
            [_datePicker setMinimumDate:[NSDate date]];
        }else{
            offsetY = offsetY + 35 + 44*2;
            [self.tableView setContentOffset:CGPointMake(0, offsetY) animated:YES];
            currentTag = indexPath.row == 0 ? kInspectionStartTimeTag : kInspectionEndTimeTag;
            _datePicker.datePickerMode = UIDatePickerModeTime;
            [_datePicker setMinimumDate:nil];
        }
        isShowDatePicker = YES;
        [UIView animateWithDuration:0.25 animations:^{
            self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-216, SCREEN_WIDTH, 216);
        }];
    }
}

#pragma mark - YWSelectBuildingTableViewControllerDelegate
-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![building.buildingId isEqualToString:currentBuilding.buildingId]) {
        currentInspectionLineOption = nil;
    }
    currentBuilding = building;
    [self.tableView reloadData];
}

#pragma mark - YWSelectInspectionLineTableViewControllerDelegate
-(void)popSelectedInspectionLine:(YWInspectionLineOption *)inspectionLineOption{
    currentInspectionLineOption = inspectionLineOption;
    [self.tableView reloadData];
}

#pragma mark - YWContactVCSelectContactDelegate
- (void)selectMultipleContact:(NSArray *)contactArray{
//    NSArray* array = [[NSArray alloc] initWithArray:contactArray];
//    self.executors = array;
    [self.executors removeAllObjects];
    [self.executors addObjectsFromArray:contactArray];
    [self.tableView reloadData];
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"send", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickSenderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}
-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker=[[UIDatePicker alloc]init];
        [_datePicker setBackgroundColor:[UIColor whiteColor]];
        _datePicker.locale =[NSLocale localeWithLocaleIdentifier:@"zh"];
        _datePicker.minuteInterval = 5;
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.navigationController.view addSubview:_datePicker];
    }
    return _datePicker;
}
-(void)dateChanged:(id)sender{
    UIDatePicker *picker = (UIDatePicker*)sender;
    NSDate *date = picker.date;
    
    NSString *format = currentTag <= kInspectionEndDateTag ? KTimeFormatDate : KTimeFormatShortTime;
    NSString *string = [YWCommonTool showTime:[date timeIntervalSince1970] andFormatter:format];//[formatter stringFromDate:date];
    if (currentTag == kInspectionStartDateTag) {
        startDate = string;
    }else if (currentTag == kInspectionEndDateTag){
        endDate = string;
    }else if (currentTag == kInspectionStartTimeTag){
        startTime = string;
    }else if (currentTag == kInspectionEndTimeTag){
        endTime = string;
    }
    [self.tableView reloadData];
}
-(void)resetDatePicker{
    isShowDatePicker = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [_datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    }];
}

#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification
{
    [self resetDatePicker];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    if (isShowDatePicker) {
        [self resetDatePicker];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self resetDatePicker];
}

- (void)clickSenderButtonEvent:(id)sender{
    [self resetDatePicker];
    if (currentBuilding==nil) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"pleaseSelect", nil),buildingShowName]];
        return;
    }
    if (currentInspectionLineOption==nil) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectInspectionLine", nil)];
        return;
    }
    if (startDate==nil||endDate ==nil||startTime==nil||endTime==nil) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"selectMissionDateAndTime", nil)];
        return;
    }
    if ([[startDate stringByReplacingOccurrencesOfString:@"-" withString:@""] integerValue]>[[endDate stringByReplacingOccurrencesOfString:@"-" withString:@""] integerValue]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"startDateMustLessThanEndDate", nil)];
        return;
    }
    if (self.executors.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectExecutor", nil)];
        return;
    }
    
    //点击发送
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToAssignMission", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self assignInspectionMission];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)assignInspectionMission{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:currentBuilding.buildingId?:@"" forKey:@"buildingId"];
    [params setValue:@(currentInspectionLineOption.inspectionLineId) forKey:@"inspectionLine.inspectionLineId"];
    
    [params setValue:startDate?:@"" forKey:@"startDate"];
    [params setValue:endDate?:@"" forKey:@"endDate"];
    [params setValue:startTime?:@"" forKey:@"startTime"];
    [params setValue:endTime?:@"" forKey:@"endTime"];
    [self.executors enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        [params setValue:@(handler.uniqueId) forKey:[NSString stringWithFormat:@"executors[%lu].uniqueId",(unsigned long)idx]];
    }];
    YWLog(@"%@",params);
    [[YWInspectionMissionManager shareManager] postInspectionMissionWithParams:params Complete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextAssignSuccess, nil)];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)clickCancelBarButtonEvent:(id)sender{
    if (currentInspectionLineOption || self.executors.count>0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"quitEditing", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
